//
//  YSStatusView.m
//  YSBookRead
//
//  Created by MOLBASE on 2018/11/8.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSStatusView.h"
#import "YSBatteryView.h"
#import "YSReaderSetting.h"
#import "YSReadHelper.h"

@interface YSStatusView ()

/// 电池
@property (nonatomic, strong) YSBatteryView *batteryView;
/// 时间
@property (nonatomic, strong) UILabel *timeLabel;
/// 计时器
@property (nonatomic, weak) NSTimer *timer;

@end

@implementation YSStatusView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews {
    self.batteryView = [[YSBatteryView alloc] init];
    self.batteryView.backColor = [[YSReaderSetting shareReaderSettings] otherTextColor];
    [self addSubview:self.batteryView];

    self.timeLabel = [[UILabel alloc] init];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    self.timeLabel.textColor = [[YSReaderSetting shareReaderSettings] otherTextColor];
    [self addSubview:self.timeLabel];

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:12];
    self.titleLabel.textColor = [[YSReaderSetting shareReaderSettings] otherTextColor];
    [self addSubview:self.titleLabel];

    [self addTimer];
    [self didChangeTime];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    self.batteryView.frame = CGRectMake(self.frame.size.width - self.batteryView.frame.size.width, (self.frame.size.height - self.batteryView.frame.size.height) / 2, self.batteryView.frame.size.width, self.batteryView.frame.size.height);

    self.timeLabel.frame = CGRectMake(CGRectGetMinX(self.batteryView.frame) - 50, 0, 50, self.frame.size.height);

    self.titleLabel.frame = CGRectMake(0, 0, CGRectGetMinX(self.timeLabel.frame), self.frame.size.height);
}

- (void)addTimer {
    if (!self.timer) {
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(didChangeTime) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        self.timer = timer;
    }
}

- (void)didChangeTime {
    self.timeLabel.text = [YSReadHelper getCurrentTimerString:@"HH:mm"];
    self.batteryView.batteryLevel = [UIDevice currentDevice].batteryLevel;
}

- (void)removeTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)dealloc {
    [self removeTimer];
}

@end
